package dc.medicine.com.okhttplib;

import android.app.Application;
import android.content.Context;
import android.os.Looper;
import android.os.Handler;


import java.util.concurrent.TimeUnit;

import dc.medicine.com.okhttplib.model.HttpHeaders;
import dc.medicine.com.okhttplib.request.PostRequest;
import okhttp3.Call;
import okhttp3.OkHttpClient;

/**
 * Created by fancl on 2016/7/14.
 */
public class OkHttpUtils  {
    public  static  final  int DEFAULT_MILLISECONDS=10000;//默认的超时时间
    private static OkHttpUtils mInstance;                 //单例

    private Handler mDelivery;//用于在主线程执行的调度器

    private OkHttpClient.Builder okHttpClientBuilder;//ok请求的客户端

    private static Application context;//全局上下文

    private HttpHeaders mCommonHeaders;                   //全局公共请求头

    private OkHttpUtils() {
        okHttpClientBuilder=new OkHttpClient.Builder();
        mDelivery = new Handler(Looper.getMainLooper());

    }

    public  static OkHttpUtils getInstance(){
        if(mInstance ==null){
            synchronized (OkHttpUtils.class){
                if(mInstance == null){
                    mInstance=new OkHttpUtils();
                }
            }
        }
        return  mInstance;
    }

    public  OkHttpClient getOkHttpClient(){
        return  okHttpClientBuilder.build();
    }

    /** 必须在全局Application先调用，获取context上下文，否则缓存无法使用 */
    public static  void init(Application app){
        context=app;
    }

    /** 获取全局上下文 */
    public static Context getContext() {
        if (context == null)
            throw new IllegalArgumentException("请先在全局Application中调用 OkHttpUtils.init() 初始化！");
        return  context;
    }

    /**
     * post请求
     */

    public  static PostRequest post(String url){
        return  new PostRequest(url);
    }

    /** 全局读取超时时间 */
    public  OkHttpUtils setReadTimeOut(int readTimeOut){
        okHttpClientBuilder.readTimeout(readTimeOut, TimeUnit.MILLISECONDS);
        return  this;
    }

    /** 全局写入超时时间 */
    public  OkHttpUtils setWriteTimeOut(int writeTimeout){
        okHttpClientBuilder.readTimeout(writeTimeout, TimeUnit.MILLISECONDS);
        return  this;
    }

    /** 全局连接超时时间 */
    public  OkHttpUtils setConnectTimeout(int connectTimeout){
        okHttpClientBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        return  this;
    }

    public Handler getDelivery() {
        return mDelivery;
    }



    /** 根据Tag取消请求 */
    public void cancelTag(Object tag) {
        for(Call call : getOkHttpClient().dispatcher().queuedCalls()){
            if(tag.equals(call.request().tag())){
                call.cancel();
            }
        }

        for( Call call :getOkHttpClient().dispatcher().runningCalls()){
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }



}
